package com.xb.ai.aop;

import cn.dev33.satoken.stp.StpUtil;
import com.xb.ai.annotation.Login;
import com.xb.ai.constant.ErrorMessage;
import com.xb.ai.exception.BusinessException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 验证用户是否登录
 */
@Aspect
@Component
public class LoginAop {

    @Pointcut("@annotation(com.xb.ai.annotation.Login)")
    private void LoginPoint() {
    }

    @Before("LoginPoint()")
    public void checkLogin(JoinPoint joinPoint) {
        // 验证用户是否登录
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        if (method.getAnnotation(Login.class) != null && !StpUtil.isLogin()) {
            throw new BusinessException(ErrorMessage.NOT_LOGIN_ERROR);
        }
    }
}
